package com.xt.controller;

import com.xt.bean.PlatformResult;
import com.xt.bean.Section;
import com.xt.service.SectionService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by XT on 2018/5/4.
 */
@RestController
@RequestMapping("/section")
public class SectionController {

    @Autowired
    SectionService ss;

    @ApiOperation(value = "新增/修改信息", notes = "新增/修改信息")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public PlatformResult insert(@ApiParam(required = true, name = "section", value = "Section实体的字段名") @RequestBody Section s) {
        //检查参数
        ss.saveOrUpdateOne(s);
        return PlatformResult.ok();
    }

    @ApiOperation(value = "删除信息", notes = "删除信息")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public PlatformResult delete(@ApiParam(required = true, name = "section", value = "Section实体的字段名") @RequestBody Section s) {
        //检查参数
        ss.deleteOne(s.getId());
        return PlatformResult.ok();
    }

    @ApiOperation(value = "根据id查", notes = "根据id查")
    @RequestMapping(value = "/getById", method = RequestMethod.GET)
    public PlatformResult getById(@ApiParam(required = true, name = "id", value = "id") @RequestParam String id) {
        Section c = ss.getById(id);
        return PlatformResult.ok(c);
    }

    @ApiOperation(value = "章节结构", notes = "查询课程知识点章节结构")
    @RequestMapping(value = "/sectionStructure", method = RequestMethod.GET)
    public PlatformResult getSectionStructure (
            @ApiParam(required = true, name = "courseId", value = "课程ID") @RequestParam String courseId,
            @ApiParam(required = true, name = "teacherId", value = "老师ID") @RequestParam String teacherId) {
        //递归拿子节点信息
        List<Section> sections = ss.getByCourseIdAndTeacherIdAndFatherIdIsNull(courseId, teacherId);
        forSections(sections);

        return PlatformResult.ok(sections);
    }

    private void forSections(List<Section> sections){
        for (Section s : sections){
            if (null != s.getHasChild() && s.getHasChild()){
                int i = sections.indexOf(s);
                sections.remove(s);
                List<Section> childs = ss.getChilds(s.getId());
                s.setChilds(childs);
                sections.add(i,s);
                forSections(childs);
            }
        }
    }

}
